package com.diandireader.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.diandireader.activity.R;
import com.diandireader.domain.DiandiReaderVO;
import com.diandireader.util.ActivityManager;
import com.diandireader.util.FileHelper;

/**
 * 阅读器ICON页面
 * @author mayh
 *
 */
public class MainReaderIconActivity extends Activity {

	private List<File> bookFileList;
	private Handler handler;
	private TableLayout tableLayout;
	private int viewType = 1;//0:列表,1:视图
	private Resources resource;
	private ImageView listBar;
	private SharedPreferences preference,bookPositionPreference;
	private File currentFile;//当前文件
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//      去掉标题栏
        this.requestWindowFeature(Window.FEATURE_NO_TITLE); 
//      去掉状态栏
//        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.reader_main_icon);
		ActivityManager.add(this);
		setViews();
		setListener();
		preference = getSharedPreferences(DiandiReaderVO.SETTING, Context.MODE_PRIVATE);
		bookPositionPreference = getSharedPreferences(DiandiReaderVO.BOOKPOSITION, Context.MODE_PRIVATE);
		resource = getResources();
		handler = new BooksHandler();
		
	}
	@Override
	protected void onResume() {
		super.onResume();
		Editor edit = preference.edit();
		edit.putString(DiandiReaderVO.VIEWTYPE, DiandiReaderVO.VIEWTYPE_ICON);
		edit.commit();
		new BookListThread().start();
	}

	//设置View
	public void setViews(){
		tableLayout = (TableLayout)findViewById(R.id.bookiconview);
		listBar = (ImageView)findViewById(R.id.listbar);
		listBar.setImageResource(R.drawable.list_bar_icon_selector);
	}
	//设置Listener
	public void setListener(){
		listBar.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent intent = new Intent();
				intent.setClass(MainReaderIconActivity.this, MainReaderListActivity.class);
				startActivity(intent);
				finish();
			}
		});
	}
	//书籍的图标模式
	public void refreshIconView(){
		//获得屏幕的宽度
		int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
		View view = View.inflate(MainReaderIconActivity.this, R.layout.bookiconitem, null);
		RelativeLayout layout = (RelativeLayout)view.findViewById(R.id.bookiconitem);
		//每个图片占的宽度 = layout的宽度+左边空格+右边空格
		int bookWidth = layout.getLayoutParams().width+10;
		//计算一行能放几个
		int counts = screenWidth/bookWidth;
		//计算能放几行
		int rows = bookFileList.size()%counts==0?bookFileList.size()/counts:bookFileList.size()/counts+1;
		int filePosition = 0;
		tableLayout.removeAllViews();
		for(int i=0;i<rows;i++){
			TableRow tableRows = new TableRow(MainReaderIconActivity.this);
			for(int j=0;j<counts;j++){
				if(filePosition<bookFileList.size()){
					view = View.inflate(MainReaderIconActivity.this, R.layout.bookiconitem, null);
					final File file = bookFileList.get(filePosition);
					TextView textView = (TextView)view.findViewById(R.id.bookname);
					ImageView imageView = (ImageView)view.findViewById(R.id.bookimage);
					textView.setText(FileHelper.getFileWithoutSuffix(file.getName()));
					String type = FileHelper.getFileType(file);
					if(FileHelper.TXT==type){
						imageView.setImageResource(R.drawable.file_txt);
					}else if(FileHelper.IMAGE==type){
						imageView.setImageResource(R.drawable.file_jpg);
					}else if(FileHelper.PDF==type){
						imageView.setImageResource(R.drawable.file_pdf);
					}else {
						imageView.setImageResource(R.drawable.unknown);
					}
					
					view.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							v.setClickable(false);
							//判断文件格式支不支持
							String fileType = FileHelper.getFileSuffix(file);
							if(!FileHelper.allowTypeList.contains(fileType)){
								Toast.makeText(MainReaderIconActivity.this, "暂不支持该格式", Toast.LENGTH_SHORT).show();
								return;
							}
							Intent intent = new Intent();
							intent.putExtra("filePath", file.getPath());
							intent.setClass(MainReaderIconActivity.this, SimpleTextReaderActivity.class);
							startActivity(intent);
						}
					});
					//添加鼠标按下和抬起效果
					view.setOnTouchListener(new OnTouchListener() {
						@Override
						public boolean onTouch(View view, MotionEvent event) {
							RelativeLayout layout = (RelativeLayout)view.findViewById(R.id.bookiconitem);
							if(event.getAction() == MotionEvent.ACTION_DOWN){
								layout.setBackgroundDrawable(resource.getDrawable(R.drawable.bookitembg_press));
							}else {
								layout.setBackgroundDrawable(resource.getDrawable(R.drawable.bookitembg_normal));
							}
							return false;
						}
					});
					//长按操作菜单
					view.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
						@Override
						public void onCreateContextMenu(ContextMenu menu, View v,
								ContextMenuInfo menuInfo) {
							menu.setHeaderTitle("选择操作");
							menu.add(0, 0, 0, "删除");
						}
					});
					//长按
					view.setOnLongClickListener(new OnLongClickListener() {
						@Override
						public boolean onLongClick(View v) {
							v.showContextMenu();
							currentFile = file;
							return true;
						}
					});
					
					tableRows.addView(view);
					filePosition++;
				}
			}
			tableLayout.addView(tableRows);
			tableLayout.setStretchAllColumns(true);
		}
	}
	
	
	//重新获得book目录的文件
	public void refreshBooks(){
		bookFileList = new ArrayList<File>();
//		获得SD卡的路径
		String storgePath = FileHelper.getStrogeFolder(); 
//		获得存放Book的目录
		File bookFolder = new File(storgePath+"/"+FileHelper.diandiReaderBooks);
		if(bookFolder!=null){
			File[] books = bookFolder.listFiles();
			if(books!=null&&books.length>0){
				for(int i=0;i<books.length;i++){
					bookFileList.add(books[i]);
				}
			}
		}
	}
	
	//线程处理文件
	 class BookListThread extends Thread {
		@Override
		public void run() {
			refreshBooks();
			//search the book of other place
			Map<String,String> filePathMap = (Map<String,String>)bookPositionPreference.getAll();
			if(!filePathMap.isEmpty()){
				Set<String> set = filePathMap.keySet();
				String path = "";
				for(String name : set){
					 path = bookPositionPreference.getString(name, "");
					 if(path!=null&&!"".equals(path)){
						 File newFile = new File(path);
						 if(newFile.exists())
							 bookFileList.add(newFile);
					 }
				}
			};
			handler.sendEmptyMessage(1);
		}
		
	}
	//handler处理
	class BooksHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 0 : {
				
			}
			break;
			case 1: {
				refreshIconView();
			}
			break;
			}
			
		}
	}
	//上下文菜单
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case 0 : {
			//删除
			AlertDialog.Builder dialog = new AlertDialog.Builder(MainReaderIconActivity.this);
			dialog.setTitle("提示");
			dialog.setMessage("是否删除该书籍?");
			dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					return;
				}
			});
			dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					FileHelper.deleteFile(currentFile);
					//delete the preference
					bookPositionPreference.edit().remove(currentFile.getName());
					//刷新列表
					new BookListThread().start();
				}
			});
			dialog.show();
		}
		break;
		case 1 : {
			
		}
		break;
		}
		return super.onContextItemSelected(item);
	}
	
	//监听按键
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		//监听取消按钮
		if(keyCode==KeyEvent.KEYCODE_BACK){
			AlertDialog.Builder builder = new AlertDialog.Builder(MainReaderIconActivity.this);
			builder.setTitle("提示");
			builder.setMessage("确定要退出么？");
			builder.setPositiveButton("确定",new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					for(Activity activity : ActivityManager.list){
						if(activity!=null)
						activity.finish();
					}
				}
			});
			builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
				}
			});
			builder.show();
		}
		return false;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "选择文件");
		menu.add(0,1,1,"网络书城");
		return super.onCreateOptionsMenu(menu);
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case 0 : {
			Intent intent = new Intent();
			intent.setClass(MainReaderIconActivity.this,FileBrowsActivity.class);
			startActivity(intent);
//			finish();
		}
		break;
		case 1 : {
			Intent intent = new Intent();
			intent.setClass(MainReaderIconActivity.this,BookMarketActivity.class);
			startActivity(intent);
		}
		break;
		}
		return false;
	}
}
